package top.fangw.gateway.hander;


import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.netty.ByteBufFlux;
import top.fangw.common.core.result.Result;

/**
 * @author fgw
 * @description 统一网关异常处理
 * @createDate 2023/11/22
 */
@Order(-1)
@Configuration
@Slf4j
public class GatewayExceptionHandler implements ErrorWebExceptionHandler {

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();

        if (exchange.getResponse().isCommitted()) {
            return Mono.error(ex);
        }


        log.error("[网关异常处理]请求路径:{},异常信息:{}", exchange.getRequest().getPath(), ex);
        return response.writeAndFlushWith(Flux.just(ByteBufFlux.just(response.bufferFactory().
                wrap(JSON.toJSONBytes(Result.failed())))));

    }
}

